//
//  EFAMoreNameVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/12.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMoreNameVC.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "EFAModel.h"
#import "ApiManager.h"

@interface EFAMoreNameVC ()

@property (weak,   nonatomic) IBOutlet UITextField *nameTextField;
@property (strong, nonatomic) UIBarButtonItem *cancelBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *saveBarBtnItem;

@end

@implementation EFAMoreNameVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 显示键盘
    [self.nameTextField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 隐藏键盘
    [self.view endEditing:YES];
}

- (void)initNavigationBar {
    NSArray *array = @[@"修改昵称", @"修改单位名称", @"修改单位地址", @"修改邮箱"];
    
    if (self.curType < array.count) {
        self.navigationItem.title = array[self.curType];
    }
    self.navigationItem.leftBarButtonItem = self.cancelBarBtnItem;
    self.navigationItem.rightBarButtonItem = self.saveBarBtnItem;
    self.saveBarBtnItem.enabled = NO;
}

- (void)initSubViews {
    NSString *placeHolder = nil;
    switch (self.curType) {
        case EFAMoreNameTypeName:
            placeHolder = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname;
            break;
        case EFAMoreNameTypeCompany:
            placeHolder = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_company;
            break;
        case EFAMoreNameTypeCompanyAddress:
            placeHolder = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_company_address;
            break;
        case EFAMoreNameTypeEmail:
            placeHolder = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_email;
            break;
        default:
            break;
    }
    
    self.nameTextField.placeholder = placeHolder;
    [self.nameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate
#pragma mark - event response
- (void)cancelBarBtnItemTapped:(UIBarButtonItem *)btnItem {
    [self goBackToParent];
}

- (void)saveBarBtnItemTapped:(UIBarButtonItem *)btnItem {
    NSArray *array = @[@"请输入昵称", @"请输入单位名称", @"请输入单位地址", @"请输入邮箱"];
    NSString *prompt = @"";
    if (self.curType < array.count) {
        prompt = array[self.curType];
    }
    if (!self.nameTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:prompt];
        return;
    }
    
    NSString *headImgUrl = nil;
    NSString *name = nil;
    NSString *company = nil;
    NSString *address = nil;
    NSString *email = nil;
    switch (self.curType) {
        case EFAMoreNameTypeName:
            name = self.nameTextField.text;
            break;
        case EFAMoreNameTypeCompany:
            company = self.nameTextField.text;
            break;
        case EFAMoreNameTypeCompanyAddress:
            address = self.nameTextField.text;
            break;
        case EFAMoreNameTypeEmail:
            email = self.nameTextField.text;
            break;
        default:
            break;
    }
    [self requestEditUserInfoWithHeadImgUrl:headImgUrl name:name company:company company_address:address email:email];
}

- (void)textFieldDidChange:(UITextField *)textField {
    // 右上角按钮的状态变化
    [self.saveBarBtnItem setEnabled:textField.text.length];
    
    // 文字长度限制
    NSInteger maxLength = (self.curType == EFAMoreNameTypeName) ? EFAGlobalNickNameMaxLength : 60;
    NSString *toBeString = textField.text;
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position || !selectedRange) {
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1) {
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}



#pragma mark - private methods
- (void)goBackToParent {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestEditUserInfoWithHeadImgUrl:(NSString *)headimg_url name:(NSString *)name company:(NSString *)company company_address:(NSString *)address email:(NSString *)email {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    headimg_url = headimg_url ? headimg_url : [EFAModel sharedInstance].loginInfo.user_info.efairyuser_headimg_url;
    name = name ? name : [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname;
    company = company ? company : [EFAModel sharedInstance].loginInfo.user_info.efairyuser_company;
    address = address ? address : [EFAModel sharedInstance].loginInfo.user_info.efairyuser_company_address;
    email = email ? email : [EFAModel sharedInstance].loginInfo.user_info.efairyuser_email;
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyuser_headimg_url" : headimg_url ? headimg_url : @"",
                           @"efairyuser_nickname" : name ? name : @"",
                           @"efairyuser_company" : company ? company : @"",
                           @"efairyuser_email" : email ? email : @"",
                           @"efairyuser_company_address" : address ? address : @""};
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiMineUserCenter] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"修改个人信息成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[EFAGlobalJsonKeyErrCode] integerValue] == 200) {
            [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname = name;
            [EFAModel sharedInstance].loginInfo.user_info.efairyuser_headimg_url = headimg_url;
            [EFAModel sharedInstance].loginInfo.user_info.efairyuser_company = company;
            [EFAModel sharedInstance].loginInfo.user_info.efairyuser_company_address = address;
            [EFAModel sharedInstance].loginInfo.user_info.efairyuser_email = email;
            [self goBackToParent];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"修改个人信息失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)cancelBarBtnItem {
    if (!_cancelBarBtnItem) {
        _cancelBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnItemTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_cancelBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    }
    return _cancelBarBtnItem;
}
- (UIBarButtonItem *)saveBarBtnItem {
    if (!_saveBarBtnItem) {
        _saveBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveBarBtnItemTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _saveBarBtnItem;
}
@end
